package top.zywork.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.zywork.annotation.SysLog;
import top.zywork.common.*;
import top.zywork.constant.FileConstants;
import top.zywork.dto.AdvertisementDTO;
import top.zywork.dto.GraphicPreferentialDTO;
import top.zywork.dto.PagerDTO;
import top.zywork.enums.DatePatternEnum;
import top.zywork.enums.ResponseStatusEnum;
import top.zywork.enums.UploadTypeEnum;
import top.zywork.ext.dos.GraphicPreferentialExtDO;
import top.zywork.ext.service.GraphicExtService;
import top.zywork.ext.service.GraphicPreferentialExtService;
import top.zywork.query.GraphicPreferentialQuery;
import top.zywork.service.GraphicPreferentialService;
import top.zywork.service.UploadService;
import top.zywork.vo.GraphicPreferentialVO;
import top.zywork.vo.PagerVO;
import top.zywork.vo.ResponseStatusVO;

import java.util.List;
import java.util.stream.Collectors;

/**
 * GraphicPreferentialController控制器类<br/>
 *
 * 创建于2020-12-02<br/>
 *
 * @author http://ljyanimo.com 刘金泳
 * @version 1.0
 */
@RestController
@RequestMapping("/graphic-preferential")
@Slf4j
public class GraphicPreferentialController extends BaseController {

    private GraphicPreferentialService graphicPreferentialService;

    @Autowired
    private GraphicPreferentialExtService graphicPreferentialExtService;

    @Autowired
    private GraphicExtService graphicExtService;

    @Value("${storage.provider}")
    private String storageProvider;

    @Value("${storage.local.compressSizes}")
    private String compressSizes;

    @Value("${storage.local.compressScales}")
    private String compressScales;

    @Value("${storage.local.advertisement.imgParentDir}")
    private String imgParentDir;

    @Value("${storage.local.advertisement.imgDir}")
    private String imgDir;

    @Value("${storage.local.advertisement.imgUrl}")
    private String imgUrl;

    @Value("${storage.local.advertisement.keepFileName}")
    private Boolean keepFileName;

    @Autowired
    private UploadService uploadService;

    @GetMapping("any/qr/{id}")
    public ResponseStatusVO qr(@PathVariable("id") Integer graphicId){
        GraphicPreferentialExtDO graphicPreferentialExtDO = graphicPreferentialExtService.getOne(new QueryWrapper<GraphicPreferentialExtDO>().eq("graphic_id", graphicId));
        return ResponseStatusVO.ok("",graphicPreferentialExtDO);
    }

    @PostMapping("admin/save")
    @SysLog(description = "后台保存GraphicPreferentialVO")
    public ResponseStatusVO save(@RequestBody @Validated GraphicPreferentialVO graphicPreferentialVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        graphicPreferentialExtService.saveOrUpdate(BeanUtils.copy(graphicPreferentialVO, GraphicPreferentialExtDO.class));
        return ResponseStatusVO.ok("添加成功", null);
    }

    @PostMapping("admin/batch-save")
    @SysLog(description = "后台批量保存GraphicPreferentialVO")
    public ResponseStatusVO saveBatch(@RequestBody @Validated List<GraphicPreferentialVO> graphicPreferentialVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        graphicPreferentialService.saveBatch(BeanUtils.copyListObj(graphicPreferentialVOList, GraphicPreferentialDTO.class));
        return ResponseStatusVO.ok("批量添加成功", null);
    }

    @GetMapping("admin/remove/{id}")
    @SysLog(description = "后台删除GraphicPreferentialVO")
    public ResponseStatusVO removeById(@PathVariable("id") Long id) {
        graphicPreferentialService.removeById(id);
        return ResponseStatusVO.ok("删除成功", null);
    }

    @PostMapping("admin/batch-remove")
    @SysLog(description = "后台批量删除GraphicPreferentialVO")
    public ResponseStatusVO removeByIds(@RequestBody String[] ids) {
        graphicPreferentialService.removeByIds(StringUtils.strArrayToLongArray(ids));
        return ResponseStatusVO.ok("批量删除成功", null);
    }

    @PostMapping("admin/update")
    @SysLog(description = "后台更新GraphicPreferentialVO")
    public ResponseStatusVO update(@RequestBody @Validated GraphicPreferentialVO graphicPreferentialVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        int updateRows = graphicPreferentialService.update(BeanUtils.copy(graphicPreferentialVO, GraphicPreferentialDTO.class));
        if (updateRows == 1) {
            return ResponseStatusVO.ok("更新成功", null);
        } else {
            return ResponseStatusVO.dataError("数据版本号有问题，在此更新前数据已被更新", null);
        }
    }

    @PostMapping("admin/batch-update")
    @SysLog(description = "后台批量更新GraphicPreferentialVO")
    public ResponseStatusVO updateBatch(@RequestBody @Validated List<GraphicPreferentialVO> graphicPreferentialVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        graphicPreferentialService.updateBatch(BeanUtils.copyListObj(graphicPreferentialVOList, GraphicPreferentialDTO.class));
        return ResponseStatusVO.ok("批量更新成功", null);
    }

    @PostMapping("admin/active")
    @SysLog(description = "后台激活或冻结GraphicPreferentialVO")
    public ResponseStatusVO active(@RequestBody GraphicPreferentialVO graphicPreferentialVO) {
        graphicPreferentialService.update(BeanUtils.copy(graphicPreferentialVO, GraphicPreferentialDTO.class));
        return ResponseStatusVO.ok("激活或冻结成功", null);
    }

    @PostMapping("admin/batch-active")
    @SysLog(description = "后台批量激活或冻结GraphicPreferentialVO")
    public ResponseStatusVO activeBatch(@RequestBody @Validated List<GraphicPreferentialVO> graphicPreferentialVOList) {
        graphicPreferentialService.updateBatch(BeanUtils.copyListObj(graphicPreferentialVOList, GraphicPreferentialDTO.class));
        return ResponseStatusVO.ok("批量激活或冻结成功", null);
    }

    @GetMapping("admin/one/{id}")
    public ResponseStatusVO getById(@PathVariable("id") Long id) {
        GraphicPreferentialVO graphicPreferentialVO = new GraphicPreferentialVO();
        Object obj = graphicPreferentialService.getById(id);
        if (obj != null) {
            graphicPreferentialVO = BeanUtils.copy(obj, GraphicPreferentialVO.class);
        }
        return ResponseStatusVO.ok("查询成功", graphicPreferentialVO);
    }

    @GetMapping("admin/all")
    public ResponseStatusVO listAll() {
        PagerDTO pagerDTO = graphicPreferentialService.listAll();
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GraphicPreferentialVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/all-cond")
    public ResponseStatusVO listAllByCondition(@RequestBody GraphicPreferentialQuery graphicPreferentialQuery) {
        PagerDTO pagerDTO = graphicPreferentialService.listAllByCondition(graphicPreferentialQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GraphicPreferentialVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/pager-cond")
    public ResponseStatusVO listPageByCondition(@RequestBody GraphicPreferentialQuery graphicPreferentialQuery) {
        PagerDTO pagerDTO = graphicPreferentialService.listPageByCondition(graphicPreferentialQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);


        List<Object> list;

        list = pagerDTO.getRows().stream().map(e->{
            GraphicPreferentialDTO graphicPreferentialDTO = (GraphicPreferentialDTO)e;
            graphicPreferentialDTO.setGraphicValue(graphicExtService.getById(graphicPreferentialDTO.getGraphicId()).getTwdmc());
            return graphicPreferentialDTO;
        }).collect(Collectors.toList());
        pagerVO.setRows(list);


        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    /**
     * 上传二维码
     * @param adId 广告编号
     * @param file 图片文件
     * @return
     */
    @PostMapping("admin/upload/{adId}")
    @SysLog(description = "上传二维码", requestParams = false)
    public ResponseStatusVO upload(@PathVariable("adId") Integer adId, MultipartFile file) {
        String date = DateFormatUtils.format(DateUtils.currentDate(), DatePatternEnum.DATE.getValue());
        UploadUtils.UploadOptions uploadOptions = UploadUtils.UploadOptions.builder().uploadParentDir(imgParentDir).uploadDir(imgDir + FileConstants.SEPARATOR + date)
                .dbSaveUrl(imgUrl + FileConstants.SEPARATOR + date).keepFileName(keepFileName).build();
        uploadOptions.generateCompressSizes(compressSizes);
        ResponseStatusVO responseStatusVO = uploadService.uploadFile(storageProvider, file, UploadTypeEnum.IMAGE.getAllowedExts(), UploadTypeEnum.IMAGE.getMaxSize(), uploadOptions);
        if (responseStatusVO.getCode().intValue() == ResponseStatusEnum.OK.getCode().intValue()) {

            GraphicPreferentialDTO graphicPreferentialDTO = GraphicPreferentialDTO.builder().id(adId).qrCode(responseStatusVO.getData().toString()).build();

            graphicPreferentialService.update(graphicPreferentialDTO);
        }
        return responseStatusVO;
    }

    /**
     * 上传QQ二维码
     * @param adId 广告编号
     * @param file 图片文件
     * @return
     */
    @PostMapping("admin/upload/qq/{adId}")
    @SysLog(description = "上传二维码", requestParams = false)
    public ResponseStatusVO uploadQq(@PathVariable("adId") Integer adId, MultipartFile file) {
        String date = DateFormatUtils.format(DateUtils.currentDate(), DatePatternEnum.DATE.getValue());
        UploadUtils.UploadOptions uploadOptions = UploadUtils.UploadOptions.builder().uploadParentDir(imgParentDir).uploadDir(imgDir + FileConstants.SEPARATOR + date)
                .dbSaveUrl(imgUrl + FileConstants.SEPARATOR + date).keepFileName(keepFileName).build();
        uploadOptions.generateCompressSizes(compressSizes);
        ResponseStatusVO responseStatusVO = uploadService.uploadFile(storageProvider, file, UploadTypeEnum.IMAGE.getAllowedExts(), UploadTypeEnum.IMAGE.getMaxSize(), uploadOptions);
        if (responseStatusVO.getCode().intValue() == ResponseStatusEnum.OK.getCode().intValue()) {

            GraphicPreferentialDTO graphicPreferentialDTO = GraphicPreferentialDTO.builder().id(adId).qqCode(responseStatusVO.getData().toString()).build();

            graphicPreferentialService.update(graphicPreferentialDTO);
        }
        return responseStatusVO;
    }


    @Autowired
    public void setGraphicPreferentialService(GraphicPreferentialService graphicPreferentialService) {
        this.graphicPreferentialService = graphicPreferentialService;
    }
}
